package com.sanpu.kxe.business.main.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.sanpu.kxe.BuildConfig;
import com.sanpu.kxe.business.main.bean.CheckVersionOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.bean.UserConfigOutput;
import com.sanpu.kxe.business.main.contract.MainContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.business.repay.bean.AreaOutput;
import com.sanpu.kxe.business.repay.model.RepayModel;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.jump.eventbus.RefreshEarningsEvent;
import com.sanpu.kxe.utils.AppContextUtil;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;

import org.greenrobot.eventbus.EventBus;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：主界面presenter
 * Created by 薛勇军 on 2018/7/9.
 */

public class MainPresenter implements MainContract.Presenter {

    private MainContract.View mView;

    private CompositeSubscription mSubscription;

    /** 是否显示过广告弹框 */
    private boolean isShowEventPopup = false;

    /** 是否显示了获取版本号 */
    private boolean isShowVersionPopup = false;

    public MainPresenter(MainContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();

        onRequestConfig();
        getAppVersionInfo();
    }

    /**
     * 获取基本配置信息
     */
    private void onRequestConfig() {
        Subscription subscription = MainModel.getInstance().userConfig()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserConfigOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(UserConfigOutput userConfigOutput) {
                        if (userConfigOutput != null) {
                            CacheManage.getInstance().saveCache(CacheModel.USER_CONFIG, userConfigOutput);
                            EventBus.getDefault().post(userConfigOutput);
                            provinces(userConfigOutput.getAdressVersion());
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onRequestUserCenter() {
        Subscription subscription = MainModel.getInstance().userCenter()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserCenterOutput>() {
                    @Override
                    public void onCompleted() {
                        mView.showAuthDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showErrorText(e);
                        showUserCenterByError();
                        mView.showAuthDialog();
                    }

                    @Override
                    public void onNext(UserCenterOutput userCenterOutput) {
                        if (userCenterOutput != null) {
                            CacheManage.getInstance().saveCache(CacheModel.USER_CENTER_KEY, userCenterOutput);
                            mView.refreshUserData(userCenterOutput);
                            mView.showPackageDialog(userCenterOutput.getActReb());
                            EventBus.getDefault().post(new RefreshEarningsEvent(userCenterOutput.isAuthorization()));
                        } else {
                            showUserCenterByError();
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取APP版本信息
     */
    private void getAppVersionInfo() {
        if (isShowVersionPopup) return;
        Subscription subscription = MainModel.getInstance().getAppVersionInfo()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CheckVersionOutput>() {
                    @Override
                    public void onCompleted() {
                        isShowVersionPopup = false;
                    }

                    @Override
                    public void onError(Throwable e) {
                        isShowVersionPopup = false;
                    }

                    @Override
                    public void onNext(CheckVersionOutput checkVersionOutput) {
                        if (checkVersionOutput != null) {
                            int latestVersion = Integer.parseInt(checkVersionOutput.getLatestVersion());
                            int currentVersion = Integer.parseInt(AppContextUtil.getVersionCode(mView.getContext()));
                            if (currentVersion < latestVersion) {
                                mView.showCheckVersionDialog(checkVersionOutput);
                                isShowVersionPopup = true;
                            }
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 获取地址省市区
     */
    private void provinces(final String version) {
        AreaOutput areaOutput = CacheManage.getInstance().getCache(CacheModel.AREA_ENTITY);
        String adressVersion = CacheManage.getInstance().getCache(CacheModel.ADRESS_VERSION);
        if (areaOutput != null && version != null && TextUtils.equals(version, adressVersion)) {
            return;
        }
        Subscription subscription = RepayModel.getInstance().provinces()
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AreaOutput>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("获取省市区", e.getMessage());
                    }

                    @Override
                    public void onNext(AreaOutput areaOutput) {
                        if (areaOutput != null) {
                            CacheManage.getInstance().saveCache(CacheModel.AREA_ENTITY, areaOutput);
                            CacheManage.getInstance().saveCache(CacheModel.ADRESS_VERSION, version);
                        }
                    }
                });
        mSubscription.add(subscription);
    }

    /**
     * 接口回调没有正常获取到数据
     */
    private void showUserCenterByError() {
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (output != null) {
            mView.refreshUserData(output);
        }
    }

    /**
     * 显示广告弹框
     */
    @Override
    public void getActHomePopup() {
//        if (!isShowEventPopup) {
//            isShowEventPopup = true;
//            Subscription subscription = MainModel.getInstance().actAppadlist()
//                    .subscribeOn(Schedulers.io())
//                    .unsubscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new Observer<List<ActHomePopOutput>>() {
//                        @Override
//                        public void onCompleted() {
//
//                        }
//
//                        @Override
//                        public void onError(Throwable e) {
//                            mView.showAuthDialog();
//                        }
//
//                        @Override
//                        public void onNext(List<ActHomePopOutput> outputs) {
//                            if (!isShowVersionPopup) {
//                                mView.showActHomePopup(outputs);
//                            }
//                        }
//                    });
//            mSubscription.add(subscription);
//        } else {
//            mView.showAuthDialog();
//        }
    }

    @Override
    public void initPush() {
        UserCenterOutput userCenterOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        String merchantCode = null;
        if (userCenterOutput != null) {
            merchantCode = userCenterOutput.getMerchantCode();
        }
        if (!TextUtils.isEmpty(merchantCode)) {
            if (BuildConfig.DEBUG) {
                XGPushConfig.enableDebug(mView.getContext(), true);
            }
            XGPushManager.bindAccount(mView.getContext(), merchantCode, new XGIOperateCallback() {
                @Override
                public void onSuccess(Object o, int i) {
                    Log.e("XGRegister", "onSuccess :" + o + " " + i + "  thread id " + Thread.currentThread().getId());
                }

                @Override
                public void onFail(Object o, int i, String s) {
                    Log.e("XGRegister", "onFail :" + o + " " + i + "  " + s);
                }
            });
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null)
            mView = null;
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
